package com.bml.client.secret.demo;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.*;
import java.util.List;

public class RemoteShellExecutor {

    private Connection conn;
    private String ip;
    private String username;
    private String password;
    private static final int TIME_OUT = 0;// 表示不超时

    /**
     * 构造函数
     *
     * @param ip       远程ip
     * @param username 远程机器用户名
     * @param password 远程机器密码
     */
    public RemoteShellExecutor(String ip, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
    }


    /**
     * 登录
     *
     * @return
     * @throws IOException
     */
    private boolean login() throws IOException {
        conn = new Connection(ip);
        conn.connect();
        return conn.authenticateWithPassword(username, password);
    }

    /**
     * 执行脚本
     *
     * @return
     * @throws Exception
     */
    public int exec(String command,ShellCallBack callBack) throws Exception {
        int ret = -1;
        try {
            if (login()) {

                //for (String command : commands) {
                    Session session = conn.openSession();
                    session.execCommand(command);
                    session.waitForCondition(ChannelCondition.STDOUT_DATA, TIME_OUT);
                   // processStdout(session.getStdout(),"utf-8");
                    callBack.doWith(session);
//                    try (InputStream stdout = session.getStdout()) {
//                        BufferedInputStream  bf = new BufferedInputStream(stdout);
//                        byte [] buffer = new byte[512];
//                        int len = 0;
//                        while ((len = (bf.read(buffer,0,buffer.length)))> 0){
//                            String str = new String(buffer,0,len);
//                            System.out.println("返回的数据="+str);
//                        }
//                    } catch (Exception ce) {
//                        ce.printStackTrace();
//                    }
               // }
                ret = session.getExitStatus();
            } else {
                throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return ret;
    }

    private  void processStdout(InputStream in, String charset){
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while((line = br.readLine()) != null){
                buffer.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            System.err.println("解析脚本出错：" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("解析脚本出错：" + e.getMessage());
            e.printStackTrace();
        }
        System.out.println("执行输出："+buffer.toString());
    }
}